package com.zixue.heima.progressNetty;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;

/**
 * @ClassName : ProtocolHttp
 * @Description : TODO
 * @Author : chunxiong
 * @Date : 2025/5/19 18:01
 * @Version 1.0
 */
@Slf4j
public class ProtocolHttp {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            new ServerBootstrap()
                    .group(boss,worker)
                    .channel(NioServerSocketChannel.class)
                    //这里得用childHandler 用Handler报错
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                            //http协议
                            ch.pipeline().addLast(new HttpServerCodec()); //编解码
//                            ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
//                                @Override
//                                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//                                    log.debug("aa:{}",msg.getClass());
//                                    //发送了1次请求默认被解析成了2个部分
//                                    //http.DefaultHttpRequest : 请求行和请求头
//                                    //http.LastHttpContent$1： 请求体
//                                    if(msg instanceof HttpContent){
//                                        log.debug("请求体:{}",msg.getClass());
//                                    }else if (msg instanceof HttpRequest){
//                                        log.debug("请求tou hang :{}",msg.getClass());
//                                    }
//                                }
//                            });
                            ch.pipeline().addLast(new SimpleChannelInboundHandler<HttpRequest>() {
                                // SimpleChannelInboundHandler<HttpRequest> 范型这里只接受这种类型
                                @Override
                                protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception {
                                    log.debug("只接受htttRequest类型：uri："+ msg.uri());

                                    //返回响应  版本
                                    DefaultFullHttpResponse defaultFullHttpResponse = new DefaultFullHttpResponse(msg.protocolVersion(), HttpResponseStatus.OK);
                                    defaultFullHttpResponse.content().writeBytes("<h1>钮扣发工资啊卧槽</h1>".getBytes());

                                    //但是一直转圈，没有告诉浏览器长度是多少， 它以为没完
                                    defaultFullHttpResponse.headers().setInt(CONTENT_LENGTH,"<h1>钮扣发工资啊卧槽</h1>".getBytes().length);
                                    //写回响应
                                    ctx.writeAndFlush(defaultFullHttpResponse);




                                }
                            });
                        }
                    })
                    .bind(8080).sync()
                    .channel()
                    .closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}
